<template>
  <div class="add-form">
    <el-dialog :title="cTitle" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules"
        ref="dataForm"
        :model="subject"
        label-position="left"
        label-width="150px"
        style="width: 80%; margin-left:10px;"
      >
        <br>
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="subject.subjectName"></el-input>
        </el-form-item>
        <br>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch v-model="subject.isFrontDisplay"></el-switch>
        </el-form-item>
        <br>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogHidden">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="hSubmit">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { update, add } from '@/api/hmmm/subjects.js'
export default {
  name: 'subjectsAdd',
  props: {
    subject: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      dialogFormVisible: false,
      // 表单验证
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    console.log(this.subject)
  },
  // 计算弹窗标题是什么
  computed: {
    cTitle () {
      return this.subject.id ? '修改学科' : '新增学科'
    }
  },
  methods: {
    // 控制弹层显示
    dialogShow () {
      this.dialogFormVisible = true
    },
    // 控制弹层隐藏
    dialogHidden () {
      this.dialogFormVisible = false
    },
    // 表单提交
    hSubmit () {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.ifSure()
        }
      })
    },
    // 表单提交选确定事件
    async ifSure () {
      // 需要判断是什么时候点的确定按钮，添加时？还是修改时？
      try {
        if (this.subject.id) {
          const res = await update(this.subject)
          console.log(res)
          this.$emit('modified')
        } else {
          const res = await add(this.subject)
          console.log(res)
          this.$emit('added')
        }
        this.dialogHidden()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>
<style scoped>
  .el-form--label-left .el-form-item__label {
    text-align: right;
  }
  .el-form-item--medium {
    margin-bottom: 22px;
  }
  .el-dialog__footer {
    text-align: center;
  }
</style>
